import { RequestConfig } from "@/.umi/plugin-request/request";
import { RequestOptionsInit } from "umi-request";
import type { ArgsProps } from "antd/lib/notification";
import { notification } from 'antd'
import { ReactNode } from "react";
import ErrorIntal from "@/components/ErrorInterceptorIntl/ErrorInterceptorIntl";

const IGNORE_ERROR_URLS: string[] = []
export function shouldIgnoreError(url: string): boolean {
    return IGNORE_ERROR_URLS.some($url => url.indexOf($url) !== -1)
}
const codeMaps: Record<number, ReactNode> = {
    400: <ErrorIntal id={ '接口不存在'} />,
    403: <ErrorIntal id={ '无权访问'} />,
    502: <ErrorIntal id={ '网关故障'} />,
    503: <ErrorIntal id={ '服务不可用，服务器暂时过载或维护'} />,
    504: <ErrorIntal id={ '网关超时'} />,
}

const notificationMessage: ArgsProps = {
    message: <ErrorIntal id={ '请求失败'}/>
}
export function globalEroorNotification(response: Response) {
    const errorDesc = codeMaps[response.status];
    if (errorDesc) {
        notificationMessage.description = errorDesc;
        notification.error(notificationMessage);
    }else{
        response.json().then((data)=>{
            return data.errors.join(',')
        }).catch(()=>{
            return response.text()
        }).then((errorMessage:string)=>{
            notificationMessage.description = errorMessage;
            notification.error(notificationMessage)
        })
    }
}
export const ErrorHandleInterceptor: Pick<RequestConfig, 'requestInterceptor' | 'responseInterceptor'> = {
    requestInterceptor: (url: string, options: RequestOptionsInit) => {
        return { url, options }
    },
    responseInterceptor: (response: Response) => {
        if (shouldIgnoreError(response.url)) {
            return response
        }
        if (`${response.status}`.startsWith('2') || `${response.status}`.startsWith('3')) {
            return response;
        }
        globalEroorNotification(response.clone());
        return response;
    }
}